package cbiz

import (
	"encoding/json"
	"fmt"
	"time"
	"xin-job/client/sconf"
	"xin-job/core/biz"
	"xin-job/core/httpclient"
)

var instance = &BizClient{
	Httpclient:  *httpclient.GetHttpclient(),
	AccessToken: sconf.ServerConf.AccessToken,
	Timeout:     time.Duration(sconf.ServerConf.Timeout),
}

func GetBizClient() *BizClient {
	return instance
}

type BizClient struct {
	Httpclient      httpclient.Httpclient
	AdminAddressUrl string
	AccessToken     string
	Timeout         time.Duration
}

// 回调定时任务的执行信息给调度中心的方法
func (c *BizClient) Callback(handleCallbackParam []*biz.HandleCallbackParam) biz.Return[string] {
	var url = c.AdminAddressUrl + "/api/callback"
	return c.exec(url, handleCallbackParam)
}

// 执行器注册自己到调度中心的方法
func (c *BizClient) Registry(registryParam *biz.RegistryParam) biz.Return[string] {
	var url = c.AdminAddressUrl + "/api/registry"
	return c.exec(url, registryParam)
}

// 执行器将自己从调度中心移除的方法
func (c *BizClient) RegistryRemove(registryParam *biz.RegistryParam) biz.Return[string] {
	var url = c.AdminAddressUrl + "/api/registryRemove"
	return c.exec(url, registryParam)
}

func (c *BizClient) exec(url string, param any) biz.Return[string] {
	body, err := json.Marshal(param)
	if err != nil {
		return biz.Return[string]{
			Code: 500,
			Msg:  fmt.Sprintf("json marshal err:%s", err.Error()),
		}
	}

	resp, err := c.Httpclient.Url(url).Body(body).Post()
	if err != nil {
		return biz.Return[string]{
			Code: 500,
			Msg:  fmt.Sprintf("send http post err:%s", err.Error()),
		}
	}

	if resp.StatusCode != 200 {
		return biz.Return[string]{
			Code: resp.StatusCode,
			Msg:  fmt.Sprintf("xxl-job remoting fail, StatusCode(%d) invalid. for url : %s", resp.StatusCode, url),
		}
	}

	var r biz.Return[string]
	err = json.Unmarshal(resp.Content, &r)
	if err != nil {
		return biz.Return[string]{
			Code: resp.StatusCode,
			Msg:  fmt.Sprintf("xxl-job json Unmarshal fail, content(%s) invalid. for url : %s", string(resp.Content), url),
		}
	}
	return r
}
